<?php
require_once(ROOT . LIBRARY .'/fields/common.inc');

class fields_image extends fields_common implements field
{
   /**
    * Normalize Value
    *
    * @param mixed $data
    * @param string $alias
    * @param array $article
    */
   public function normalizeValue($value, $lang = null)
   {
      $this->value = unserialize($value);
      
      return $this->value;
   }


   /**
    * Get HTML code for Image fields
    *
    * @param array $value
    * @return string
    */
   public function getFieldHTML($data)
   {
      $value = is_object($data) ? $data->{$this->alias}(null) : NULL;

      if(!empty($value)) $value = reset($value);
      
      $html  = '<div id="addThumbHref_'. $this->alias . (!empty($this->fieldset) ? (!empty($data->id) ? $data->id : $this->fieldset) : '') .'">'.EOL;
      if($value)
      {
         $html .= '<img src="'. $value['src'] .'?' . time() . '" width="'. $value['0'] .'" height="'. $value['1'] .'" alt="" />'.EOL;
      }
      $html .= '<div>';
      $html .= '<a href="/admin/thumbnailing.php" title="'. gettext::translate('fields', $this->lang_phrase) .'" onclick="return loadCropper(this, '. $this->id;
      $html .= ',\'addThumbHref_'. $this->alias  . (!empty($this->fieldset) ? (!empty($data->id) ? $data->id : $this->fieldset) : '') .'\');">';
      $html .= '<input type="hidden" name="f['. $this->alias .']';
      if(!empty($this->fieldset)) $html .= '['. (!empty($data->id) ? $data->id : $this->fieldset) .']';
      $html .= '" id="f_'. $this->alias;
      if(!empty($this->fieldset)) $html .= '_'. (!empty($data->id) ? $data->id : $this->fieldset);
      $html .= '" />';
      $html .= '<img src="/tpa/img/48/image_add.png" width="48" height="48" align="left" alt="'. gettext::translate('meccano','addthumb') .'"';
      $html .= ' title="'. gettext::translate('meccano','addthumb') . '" rel="button"';
      if($value) $html .= ' style="display:none;"';
      $html .= ' /></a>'.EOL;
      if(empty($this->fieldset))
      {
         $html .= '<span class="fl-left" style="margin:10px 0 0 20px;';
         if(!$value) $html .= 'display:none;';
         $html .= '" rel="del_img"><a href="" class="a_icon i_delete" onclick="DelThumb(this);return false;">';
         $html .= gettext::translate('meccano','delete') .'</a></span>';
         $html .= '<div class="clear"></div>';
      }
      $html .= '</div></div>';

      return $html;
   }

   public function validateInput($value, $dataObject = NULL)
   {
      // DELETE IMAGE
      if($value == 'delete' && property_exists($this, 'value'))
      {
         if(is_array($this->value))
         {
            foreach($this->value AS $image)
            {
               if(!empty($image['src']) && file_exists(ROOT . $image['src']))
               {
                  unlink(ROOT . $image['src']);
               }
            }
         }

         $this->value = NULL;
      }

      // ADD IMAGE
      if(!empty($value))
      {
         parse_str($value);
         $value     = array();
         $forunlink = array();

         if(!empty($crop))
         {
            foreach($this->images AS $key=>$params)
            {
               # Is images params (not meta params)
               if(!is_numeric($key)) continue;

               # if isn't exists any src image - break
               $path_src = is_array($path) ? (isset($path[$key]) ? $path[$key] : $path[0]) : $path;
               if(!file_exists(ROOT . TMP_FOLDER .'/'. basename($path_src))) break;

               # prepare file names and destinations
               $fileinfo         = getimagesize(ROOT . TMP_FOLDER . '/' . basename($path_src));
               $source_file      = ROOT . TMP_FOLDER .'/'. basename($path_src);
               $dataObject_ID    = $dataObject->trueID();
               if(get_class($dataObject) == 'user')
               {
                  $destination_dir  = IMAGES .'/user';
               } else
               {
                  $destination_dir  = $dataObject->cat ? $dataObject->cat : $dataObject_ID;
                  $destination_dir  = IMAGES . '/' . (!empty($destination_dir) ? ceil($destination_dir / 50) : 'lost');
               }
               $destination_file = $this->belong .'_';
               $file_extention   = '.'. substr(strrchr(basename($path_src), '.'), 1);

               if(!is_dir(ROOT . $destination_dir)) mkdir(ROOT . $destination_dir);

               if($this->fieldset)
               {
                  $destination_file .= substr(md5($this->alias. $path_src), 0, 8) .'_'. $dataObject->cat;
               } else
               {
                  $destination_file .= substr(md5($this->alias), 0, 5) .'_'. $dataObject_ID;
               }


               $image_file = $destination_file .'_'. $key . $file_extention;

               if(isset($crop[$key]))
               {
                  $w = isset($crop[$key]['w']) ? intval($crop[$key]['w']) : $params['max_w'];
                  $h = isset($crop[$key]['h']) ? intval($crop[$key]['h']) : $params['max_h'];
                  $x = isset($crop[$key]['x']) ? intval($crop[$key]['x']) : 0;
                  $y = isset($crop[$key]['y']) ? intval($crop[$key]['y']) : 0;

                  if($w && $h)
                  {
                     copy($source_file, ROOT . $destination_dir .'/'. $image_file);
                     $operate_file = ROOT . $destination_dir .'/'. $image_file;

                     if ($w < $fileinfo[0] || $h < $fileinfo[1] || $x || $y)
                     {
                        crop_iMagick($operate_file, $operate_file, $w, $h, $x, $y);
                     }

                     if($w > $params['max_w'] || $h > $params['max_h'])
                     {
                        $data = resize_iMagick($operate_file, $operate_file, $params['max_w'], $params['max_h'], 2);
                     }

                     $value[$key] = getimagesize($operate_file);
                     $value[$key]['src'] = $destination_dir .'/'. $image_file;
                  }
               }

               $forunlink[] = $source_file;
            }
         }

         $forunlink = array_values($forunlink);
         foreach($forunlink AS $image) if(file_exists($image)) unlink($image);

      } elseif(property_exists($this, 'value'))
      {
         $value = $this->value;
      } else
      {
         $value = NULL;
      }

      $this->value = $value;
      
      return $this->value;
   }

   public function saveValue($lang = NULL)
   {
      if(property_exists($this, 'value'))
      {
         return mysql_real_escape_string(serialize($this->value));
      }

      return '';
   }

   public function sweep()
   {
      if(!empty($this->value))
      {
         foreach($this->value AS $img)
         {
            if(file_exists(ROOT . $img['src']))
            {
               unlink(ROOT . $img['src']);
            }
         }
      }
   }


   public function value($selector = NULL)
   {
      $v = parent::value($selector);

      if($selector !== FALSE && $selector !== NULL && is_array($v))
      {
         if(is_numeric($selector) && isset($v[$selector]))
         {
            $v = $v[$selector];
         } else
         {
            $selector = explode('|', $selector);
            if(sizeof($selector) == 2 && isset($v[$selector[0]]) && isset($v[$selector[0]][$selector[1]]))
            {
               $v = $v[$selector[0]][$selector[1]];
            }
         }
      }

      return $v;
   }
}
